
// ASUIDlg.cpp : implementation file
//

#include "stdafx.h"
#include "ASUI.h"
#include "ASUIDlg.h"
#include "Pict.h"
#include "IReadingInformation.h"
#include "DummyReadingInformation.h"
#include "ITime.h"
#include "Time.h"
#include "IReading.h"
#include "afxdialogex.h"
#include "History.h"
#include "HistoryGraph.h"
#include <string>
#include <list>
#include <set>
#include <memory>

using namespace std;
#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CAboutDlg dialog used for App About

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };
	CPict	networkGraph;
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CASUIDlg dialog




CASUIDlg::CASUIDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CASUIDlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CASUIDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_LIST1, ListCtrl);
	DDX_Control(pDX, IDC_Chart, networkGraph);
}

BEGIN_MESSAGE_MAP(CASUIDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDOK, &CASUIDlg::OnBnClickedOk)
	ON_WM_TIMER()
END_MESSAGE_MAP()


// CASUIDlg message handlers

BOOL CASUIDlg::OnInitDialog()
{
	CDialog::OnInitDialog();
	oldId = -1;
	// Add "About..." menu item to system menu.

	strcpy(toolTipMsg,"");
	// Add "About..." menu item to system menu.
	
	if( !m_ToolTip.Create(this))
	{
	   TRACE0("Unable to create the ToolTip!");
	}
	else
	{
	  // Add tool tips to the controls, either by hard coded string 
	  // or using the string table resource
		m_ToolTip.SetMaxTipWidth(200);
		m_ToolTip.AddTool( &networkGraph, _T(toolTipMsg));
		m_ToolTip.Activate(TRUE);
	}
     
	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	SetTimer(1, 1000, nullptr); // Setup a timer to fire every second

	ListCtrl.InsertColumn(0,"Node ID",0,60,-1);

	std::set<std::string> readingTypes = ReadingInfo->getReadingTypes();
	int i=1;
	for (std::set<std::string>::iterator iter = readingTypes.begin(); iter != readingTypes.end(); iter++) {
		string readingType = *iter;
		if (readingType != "Parent") {
			ListCtrl.InsertColumn(i++, readingType.c_str(), 0, 60, -1);
		}
	}

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CASUIDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CASUIDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CASUIDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}



void CASUIDlg::OnBnClickedOk()
{
	// TODO: Add your control notification handler code here
	//CDialog::OnOK();

   HistoryGraph aboutDlg;
   aboutDlg.setReadingInformation(ReadingInfo);
   aboutDlg.DoModal();

}



void CASUIDlg::OnTimer(UINT_PTR nIDEvent)
{
	ReadingInfo->update(); // FIXME: where should this go?

	ListCtrl.DeleteAllItems();

	std::set<std::string> readingTypes = ReadingInfo->getReadingTypes();
	
	LVITEM lvItem;
	lvItem.iSubItem = 0;
	lvItem.mask = LVIF_TEXT;
	string result;
	char res[80];
	ListCtrl.SetExtendedStyle(LVS_EX_GRIDLINES);

	Time endTime;
	Time startTime(endTime.getUnixTime() - 60);

	int row;
	Time now;
	std::set<int> ids = ReadingInfo->getSensorIds(startTime, endTime);
	
	for (std::set<int>::iterator iter = ids.begin(); iter != ids.end(); iter++) {
		std::set<int> p;
		int currentId = *iter;
		std::list<unique_ptr<Sensor::IReading>> parent = ReadingInfo->getReading(currentId,"Parent",startTime,endTime);
		if(parent.size() != 0)
		{
			networkGraph.addEdge(currentId,parent.front()->getValue());
			networkGraph.Invalidate(1);
		}
		// First column
		row = 0;
		lvItem.iItem = row;
		lvItem.iSubItem = 0;
		itoa(currentId, res, 10);
		lvItem.pszText = res;
		ListCtrl.InsertItem(&lvItem);

		// Remaining columns
		int col = 1;
		for (std::set<string>::iterator readingTypeIter = readingTypes.begin(); readingTypeIter != readingTypes.end(); readingTypeIter++) {
			std::string readingType = *readingTypeIter;
			if (readingType != "Parent") {
				std::list<unique_ptr<Sensor::IReading>> readings = ReadingInfo->getReading(
					currentId,
					readingType,
					startTime,
					endTime
				);

				lvItem.iItem = row;
				lvItem.iSubItem = col;

				if (readings.size() > 0) {
					std::sprintf(res,"%0.1f",readings.front()->getValue());
					lvItem.pszText = res;
				} else {
					lvItem.pszText = "--";
				}

				ListCtrl.SetItem(&lvItem);

				col++;			
			}
		}
		row++;
		
	}
	networkGraph.setNodeIds(ids);
	if(networkGraph.getId() != -1&& oldId != networkGraph.getId())
	{
		oldId = networkGraph.getId();
		 
		strcpy(toolTipMsg, "Node ID: ");
		char temp[5];
		itoa(oldId, temp,10);
		strcat(toolTipMsg,temp);
		for (std::set<string>::iterator readingTypeIter = readingTypes.begin(); readingTypeIter != readingTypes.end(); readingTypeIter++)
		{
			std::string readingType = *readingTypeIter;
			std::list<unique_ptr<Sensor::IReading>> readings = ReadingInfo->getReading(
				oldId,
				readingType,
				startTime,
				endTime
			);

			strcat(toolTipMsg,"\r");
			strcat(toolTipMsg, readingType.c_str());
			strcat(toolTipMsg, ": ");
			if (readings.size() > 0) 
			{
				char tempReading[10];
				std::sprintf(tempReading,"%0.1f",readings.front()->getValue());
				strcat(toolTipMsg, tempReading);
			}
			
		}

	
		m_ToolTip.DelTool(&networkGraph);
		m_ToolTip.AddTool( &networkGraph, _T(toolTipMsg));
	
	}
	if (networkGraph.getId()==-1)
	{
		strcpy(toolTipMsg, "");
		m_ToolTip.DelTool(&networkGraph);
		m_ToolTip.AddTool( &networkGraph, _T(toolTipMsg));
	}
	CDialog::OnTimer(nIDEvent);
	networkGraph.Invalidate(1);
	
}

BOOL CASUIDlg::PreTranslateMessage(MSG* pMsg)
{
     m_ToolTip.RelayEvent(pMsg);

     return CDialog::PreTranslateMessage(pMsg);
}